package com.wlbx.agent.util.fingerprint;

import java.util.List;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import com.wlbx.agent.ui.activity.LoginActivity;

public class JudgeFingureService extends Service {

	private int countnumber = 0;
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	
	
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		new Thread(){
			public void run() {
				try {
					while(true){
					Thread.sleep(1000);
					if(isAppOnForeground()){
						if(countnumber>30){
							if(!"com.wlbx.agent.ui.activity.LoginActivity".equals(listActivity())){
								Intent myintent = new Intent();
								myintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								myintent.setClass(getApplicationContext(), LoginActivity.class);
								startActivity(myintent);
							}
							countnumber = 0;
						}else{
							countnumber = 0;
						}
					}else{
						countnumber ++;
					}
					}
					
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			};
			
		}.start();
	}

	public boolean isAppOnForeground() {
		ActivityManager systemService = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningAppProcessInfo> runningAppProcesses = systemService.getRunningAppProcesses();
		if(runningAppProcesses==null) return false;
		for(RunningAppProcessInfo processes: runningAppProcesses){
			if(processes.processName.equals("com.wlbx.agent")&&processes.importance==RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
				return true;
			}
		}
		return false;
	}

	public  String listActivity(){
		ActivityManager systemService = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> runningTasks = systemService.getRunningTasks(1);
		RunningTaskInfo runningTaskInfo = runningTasks.get(0);
		ComponentName component = runningTaskInfo.topActivity;
		String className = component.getClassName();
		return className;
	}

}
